import { UserInfo } from "./auth";

// API配置文件
export const API_CONFIG = {
  // 基础URL - 请替换为您的实际API地址
  BASE_URL: 'http://localhost:8071/salon',
  
  // 产品相关接口
  PRODUCT: {
    LIST: '/product/list',
    DETAIL: '/product/detail',
    CATEGORY_LIST: '/productCategory/list'
  },
  
  // 服务相关接口
  SERVICE: {
    LIST: '/project/list',
    DETAIL: '/project/query',
    CATEGORY_LIST: '/projectCategory/list',
    BEAUTICIAN_LIST: '/project/beautician'
  },
  
  // 预约相关接口
  APPOINTMENT: {
    CREATE: '/appointment/add',
    LIST: '/appointment/list',
    CANCEL: '/appointment/cancel'
  },
  
  // 用户相关接口
  USER: {
    INFO: '/user/info',
    UPDATE: '/user/update',
    LOGIN: '/user/login'
  },
  
  // 购物车相关接口
  CART: {
    ADD: '/cart/add',
    LIST: '/cart/list',
    UPDATE: '/cart/update',
    REMOVE: '/cart/remove'
  },
  
  // 订单相关接口
  ORDER: {
    CREATE: '/order/create',
    LIST: '/order/list',
    DETAIL: '/order/detail',
    PAY: '/order/pay'
  },

  MEMBER: {
    LOGIN: '/member/login'
  },

  // 销售相关接口
  SALE: {
    PURCHASE: '/sale/purchase',
    MY_PURCHASES: '/sale/myPurchases'
  }
}

// 请求封装
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

// 通用的请求方法
export function request<T>(options: {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
}): Promise<ApiResponse<T>> {
  // 获取token
  const token = wx.getStorageSync('token')
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: API_CONFIG.BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if(res.data.code == 1004) {
            // 提示登录失效
            wx.showToast({
              title: '登录失效，请重新登录',
              icon: 'none'
            })
            // 清除token
            wx.removeStorageSync('token')
            // 清除用户信息
            wx.removeStorageSync('userInfo')
            // 跳转登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            })
          } else {
            resolve(res.data as ApiResponse<T>)
          }
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export const userApi = {
  // 登录
  async login(username: string, password: string) {
    return request<{
      token: string;
      userInfo: UserInfo;
    }>({
      url: API_CONFIG.USER.LOGIN,
      method: 'POST',
      data: {
        username,
        password
      }
    })
  }
}

// 小程序用户相关
export const memberApi = {
  // 登录
  async login(username: string, password: string) {
    return request<{
      token: string;
      member: MemberInfo;
    }>({
      url: API_CONFIG.MEMBER.LOGIN,
      method: 'POST',
      data: {
        name: username,
        password
      }
    })
  }
}

// 预约相关
export const appointmentApi = {
  // 预约
  async createAppointment(params: {
    projectId: number;
    beauticianId: number;
    appointmentDate: string;
  }) {
    return request<{
      id: number;
    }>({
      url: API_CONFIG.APPOINTMENT.CREATE,
      method: 'POST',
      data: params
    })
  },

  // 获取预约列表
  async getAppointmentList(params: {
    status: string;
  }) {
    return request<{
      id: number;
      projectId: number;
      beauticianId: number;
      appointmentDate: string;
      status: string;
      notes: string;
    }[]>({
      url: API_CONFIG.APPOINTMENT.LIST,
      method: 'POST',
      data: params
    })
  },

  // 取消预约
  async cancelAppointment(id: number) {
    return request<{
      id: number;
    }>({
      url: `${API_CONFIG.APPOINTMENT.CANCEL}`,
      method: 'POST',
      data: {
        id
      }
    })
  },
}

// 商品相关API
export const productApi = {
  // 获取产品详情
  async getProductDetail(id: number) {
    return request<Product>({
      url: `${API_CONFIG.PRODUCT.DETAIL}/${id}`,
      method: 'GET'
    })
  },
  
  // 获取产品分类
  async getProductCategories() {
    return request<ProductCategory[]>({
      url: API_CONFIG.PRODUCT.CATEGORY_LIST,
      method: 'POST'
    })
  },

  // getProductList  
  async getProductList(params) {
    return request<Product[]>({
      url: API_CONFIG.PRODUCT.LIST,
      method: 'POST',
      data: params
    })
  }
}

// 美容产品购买
export const saleApi = {
  // 购买
  async purchase(params: any) {
    return request({
      url: API_CONFIG.SALE.PURCHASE,
      method: 'POST',
      data: params
    })
  },

  // 我的购买
  async getMyPurchases(params?: { memberId: number }) {
    return request({
      url: API_CONFIG.SALE.MY_PURCHASES,
      method: 'POST',
      data: params
    })
  }
}

// 服务相关API
export const serviceApi = {
  // 获取服务列表
  async getServiceList(params?: {
    category?: string;
    keyword?: string;
    page?: number;
    size?: number;
  }) {
    return request<Service[]>({
      url: API_CONFIG.SERVICE.LIST,
      method: 'GET',
      data: params
    })
  },
  
  // 获取服务详情
  async getServiceDetail(id: number) {
    return request<Service>({
      url: `${API_CONFIG.SERVICE.DETAIL}`,
      method: 'POST',
      data: {
        id
      }
    })
  },
 
  // 获取服务分类
  async getServiceCategories() {
    return request<ServiceCategory[]>({
      url: API_CONFIG.SERVICE.CATEGORY_LIST,
      method: 'GET'
    })
  },

  // 获取服务对应的美容师
  async getServiceBeauticians(serviceId: number) {
    return request<Beautician[]>({
      url: API_CONFIG.SERVICE.BEAUTICIAN_LIST,
      method: 'POST',
      data: {
        id: serviceId
      }
    })
  }
}

// 类型定义
export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  originalPrice: number;
  category: string;
  categoryName: string;
  sales: number;
  rating: number;
  image: string;
  stock: number;
  images?: string[];
  specifications?: {
    key: string;
    value: string;
  }[];
}

export interface ProductCategory {
  id: string;
  name: string;
  code: string;
  sort: number;
  icon?: string;
}

export interface Service {
  id: number;
  name: string;
  description: string;
  price: number;
  duration: number;
  category: string;
  categoryName: string;
  sales: number;
  rating: number;
  imageUrl: string;
}

export interface ServiceCategory {
  id: string;
  name: string;
  code: string;
  sort: number;
  icon?: string;
}

export interface Beautician {
  id: number;
  name: string;
  imageUrl: string;
  experience: number;
  rating: number;
}

export interface Booking {
  id: number;
  serviceId: number;
  serviceName: string;
  date: string;
  time: string;
  price: number;
  status: 'pending' | 'confirmed' | 'completed' | 'cancelled';
  customerName: string;
  customerPhone: string;
  notes?: string;
}

export interface CartItem {
  id: number;
  name: string;
  price: number;
  image: string;
  quantity: number;
  selected: boolean;
  stock: number;
}

export interface Order {
  id: number;
  orderNo: string;
  items: CartItem[];
  totalPrice: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  createTime: string;
  address: {
    name: string;
    phone: string;
    address: string;
  };
}

export interface MemberInfo {
  id: number;
  name: string;
  phone: string;
  memberLevel: string;
  points: number;
  balance: number;
  createTime: string;
}